package icontext

/*

#cgo CFLAGS: -I../../../src_c -I../../../src_c/web_svc/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "appconfig.h"
#include "web_server.h"
#include "rrd.h"
#include "log.h"

*/
import "C"

import (
	"github.com/prometheus/procfs"
)

var pfs procfs.FS

func InitSystem() error {
	var err error

	pfs, err = procfs.NewDefaultFS()
	if err != nil {
		return err
	}

	return nil
}

func updateSystemStat() {
	updateSysCpuStat()
	updateSysMemStat()
}

func updateSysCpuStat() {
	stat, err := pfs.Stat()
	if err != nil {
		return
	}
	// fmt.Println("CPUTotal:", stat.CPUTotal)
	dataAttr := &webDataAttr[WEB_DATA_TYPE_SYS_CPU]
	st := C.rrdset_find_bytype(dataAttr.Family, dataAttr.Type)
	if st == nil {
		return
	}
	C.rrdset_next(st)

	RrddimFindAndSet(st, "user", dataAttr, C.longlong(stat.CPUTotal.User))
	RrddimFindAndSet(st, "system", dataAttr, C.longlong(stat.CPUTotal.System))
	RrddimFindAndSet(st, "idle", dataAttr, C.longlong(stat.CPUTotal.Idle))
	RrddimFindAndSet(st, "iowait", dataAttr, C.longlong(stat.CPUTotal.Iowait))
	RrddimFindAndSet(st, "irq", dataAttr, C.longlong(stat.CPUTotal.IRQ))
	RrddimFindAndSet(st, "softirq", dataAttr, C.longlong(stat.CPUTotal.SoftIRQ))

	C.rrdset_done(st)
}

func updateSysMemStat() {
	stat, err := pfs.Meminfo()
	if err != nil {
		return
	}
	// fmt.Println("MEM:", stat)
	dataAttr := &webDataAttr[WEB_DATA_TYPE_SYS_MEM]
	st := C.rrdset_find_bytype(dataAttr.Family, dataAttr.Type)
	if st == nil {
		return
	}
	C.rrdset_next(st)

	if stat.MemTotal != nil {
		RrddimFindAndSet(st, "total", dataAttr, C.longlong(*stat.MemTotal))
	}
	if stat.MemAvailable != nil {
		RrddimFindAndSet(st, "available", dataAttr, C.longlong(*stat.MemAvailable))
	}

	C.rrdset_done(st)
}
